package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        if (blogId == null) {
            List<Blog>blogs = blogDao.getBlog();
            String respJson = mapper.writeValueAsString(blogs);
            resp.setContentType("application/json;charset =utf-8");
            resp.getWriter().print(respJson);
        }else {
            Blog blog= blogDao.getBlog(Integer.parseInt(blogId));
            if (blog == null) {
                blog = new Blog();
            }
            String Json = mapper.writeValueAsString(blog);
            resp.setContentType("application/json;charset =utf-8");
            resp.getWriter().print(Json);
        }

    }
}
